<script lang="ts" setup>
import { ref, reactive } from "vue"
import { useUserStore } from "@/store/modules/user"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { updateAgencyDataApi, updatechangePasswordApi, updateApiKD, updateApiCL } from "@/api/user"
import { checkID, checkName } from "@/utils/validate"
import useClipboard from "vue-clipboard3"
import { useRouter } from "vue-router"
import { checkPw } from "@/utils/validate"
import { useCommonStore } from "@/store/modules/common"
const router = useRouter()
import vueQr from "vue-qr/src/packages/vue-qr.vue"
const dialogVisible = ref(false)
const dialogVisibleA = ref(false)
const ruleFormRef = ref<FormInstance>()
const userStore = useUserStore()
const commonStore = useCommonStore()
const link = ref<string>(`${commonStore.BASEURL}/retail/#/register?tid=${userStore.userInfo.user_invite}`)
// 查个人数据
const tableData = ref<any>()
tableData.value = userStore.userInfo
console.log(tableData.value, "获取用户信息")

// 表单验证
const rules = reactive<FormRules>({
  user_card_name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { required: true, validator: checkName, trigger: "blur" }
  ],
  user_sex: [{ required: true, message: "请输入性别", trigger: "blur" }],
  user_card_id: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    { required: true, validator: checkID, trigger: "blur" }
  ],
  old_password: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
  new_password: [{ required: true, validator: checkPw, trigger: "blur" }]
})

// #region 修改用户的个人信息
const ruleForm = reactive<any>({
  user_name: tableData.value.user_name,
  user_card_name: tableData.value.user_card_name,
  user_sex: tableData.value.user_sex,
  user_card_id: tableData.value.user_card_id,
  user_mobile: tableData.value.user_mobile,
  user_key: tableData.value.user_key,
  user_super: tableData.value.user_super,
  user_level: tableData.value.user_level,
  user_id: tableData.value.user_id,
  user_invite: tableData.value.user_invite,
  user_one: tableData.value.user_one,
  user_over: tableData.value.user_over
})
const addXG = () => {
  dialogVisible.value = true
}
// 确认表单按钮
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!")
      const data = ref<any>()
      data.value = ruleForm
      // data.value.user_id = Number(data.value.user_id) + 1000
      updateAgencyDataApi(data.value).then(() => {
        location.reload()
      })
    } else {
      console.log("error submit!", fields)
    }
  })
}
// 取消按钮
const resetForm = () => {
  clearValidate()
  dialogVisible.value = false
}
// #endregion

//  #region 修改账号的密码
const ruleFormA = reactive({
  old_password: "",
  new_password: ""
})
const addXGPassword = () => {
  dialogVisibleA.value = true
}
const logout = () => {
  userStore.logout()
  router.push("/login")
}
// 确认表单按钮
const submitFormA = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      updatechangePasswordApi(ruleFormA).then(() => {
        ElMessage.success("修改成功")
        dialogVisibleA.value = false
        setTimeout(() => {
          logout()
        }, 1000)
      })
    } else {
      console.log("error submit!", fields)
    }
  })
}

// 取消按钮
const resetFormA = () => {
  clearValidate()
  dialogVisibleA.value = false
}
// #endregion

// ** 清除规则报错信息
const clearValidate = () => {
  ruleFormRef.value?.resetFields()
}

const { toClipboard } = useClipboard()
const copy = async (text: string) => {
  try {
    await toClipboard(text) //实现复制
    ElMessage.success("已复制！")
  } catch (e) {
    console.error(e)
  }
}

// 下载宽带对接文档
const downLoadKD = () => {
  updateApiKD().then((res: any) => {
    const blob = new Blob([res.data], {
      type: "application/docx;charset=utf-8"
    })
    const downloadElement = document.createElement("a")
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = "宽带对接文档.docx"
    document.body.appendChild(downloadElement)
    downloadElement.click()
    window.URL.revokeObjectURL(href)
  })
}
// 下载存量对接文档
const downLoadCL = () => {
  updateApiCL().then((res: any) => {
    const blob = new Blob([res.data], {
      type: "application/docx;charset=utf-8"
    })
    const downloadElement = document.createElement("a")
    const href = window.URL.createObjectURL(blob)
    downloadElement.href = href
    downloadElement.download = "存量对接文档.docx"
    document.body.appendChild(downloadElement)
    downloadElement.click()
    window.URL.revokeObjectURL(href)
  })
}
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-row>
        <el-col :span="12">
          <el-form ref="ruleFormRef" :model="tableData" :rules="rules" label-width="120px" class="frame" status-icon>
            <el-form-item label="账号" prop="user_name">
              <el-input v-model="tableData.user_name" disabled />
            </el-form-item>
            <el-form-item label="姓名" prop="user_card_name">
              <el-input v-model="tableData.user_card_name" disabled />
            </el-form-item>
            <el-form-item label="性别" prop="user_sex">
              <el-input v-model="tableData.user_sex" disabled />
            </el-form-item>
            <el-form-item label="身份证号" prop="user_card_id">
              <el-input v-model="tableData.user_card_id" disabled />
            </el-form-item>
            <el-form-item label="手机号码" prop="user_mobile">
              <el-input v-model="tableData.user_mobile" disabled />
            </el-form-item>
            <el-form-item label="key" prop="user_key" style="width: 370px">
              <el-input v-model="tableData.user_key" disabled type="textarea" />
              <el-link type="primary" style="margin-left: 10px" @click="copy(tableData.user_key)"><el-icon>
                  <DocumentCopy />
                </el-icon>复制</el-link>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addXG"> 修改信息 </el-button>
              <el-button type="primary" @click="addXGPassword"> 修改密码 </el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="12">
          <div style="margin-bottom: 20px">
            <span>邀请码：</span>
            <el-link>{{ userStore.userInfo.user_invite }}</el-link>
            <el-link type="primary" style="margin-left: 10px" @click="copy(userStore.userInfo.user_invite)"><el-icon>
                <DocumentCopy />
              </el-icon>复制</el-link>
          </div>
          <div>
            <span>邀请链接：</span>
            <el-link>{{ link }}</el-link>
            <el-link type="primary" style="margin-left: 10px" @click="copy(link)"><el-icon>
                <DocumentCopy />
              </el-icon>复制</el-link>
          </div>
          <div style="margin-top: 30px">
            <span style="vertical-align: top">邀请二维码：</span>
            <vue-qr :text="link" :size="200" />
          </div>
          <div>
            <span>号卡对接文档：</span>
            <el-link type="primary" target="_blank"
              href="https://apifox.com/apidoc/shared-c2108bc0-3d70-405d-a4f5-e6e80f0e174f">分销系统对接API点击前往</el-link>

            <span style="margin-left: 20px">文档密码: qCqmf7iD</span>
            <el-link type="primary" style="margin-left: 10px" @click="copy('qCqmf7iD')"><el-icon>
                <DocumentCopy />
              </el-icon>复制</el-link>
          </div>

          <!-- <div>
            <span>宽带对接文档：</span>
            <el-link type="primary" target="_blank" @click="downLoadKD">点击下载</el-link>
          </div>
          <div>
            <span>存量对接文档：</span>
            <el-link type="primary" target="_blank" @click="downLoadCL">点击下载</el-link>
          </div> -->
        </el-col>
      </el-row>
    </el-card>
    <!-- 个人信息弹出框 -->
    <el-dialog v-model="dialogVisible" width="40%" @closed="resetForm">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon
        @keyup.enter="submitForm(ruleFormRef)">
        <el-form-item label="姓名" prop="user_card_name">
          <el-input v-model="ruleForm.user_card_name" />
        </el-form-item>
        <el-form-item label="性别" prop="user_sex">
          <el-select v-model="ruleForm.user_sex" placeholder="请选择性别">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="user_card_id">
          <el-input v-model="ruleForm.user_card_id" />
        </el-form-item>
        <el-form-item label="手机号码" prop="user_mobile">
          <el-input v-model="ruleForm.user_mobile" />
        </el-form-item>
        <!-- <el-form-item label="密码" prop="user_password">
          <el-input v-model="ruleForm.user_password" />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click.prevent="submitForm(ruleFormRef)"> 确认 </el-button>
          <el-button @click="resetForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 修改密码弹出框 -->
    <el-dialog v-model="dialogVisibleA" width="40%" @closed="resetFormA">
      <el-form ref="ruleFormRef" :model="ruleFormA" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon
        @keyup.enter="submitFormA(ruleFormRef)">
        <el-form-item label="旧密码" prop="old_password">
          <el-input v-model="ruleFormA.old_password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="new_password">
          <el-input v-model="ruleFormA.new_password" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.prevent="submitFormA(ruleFormRef)"> 确认 </el-button>
          <el-button @click="resetFormA">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.frame {
  .el-form-item {
    .el-input {
      width: 250px;
    }
  }
}
</style>
